from ws4py.client.threadedclient import WebSocketClient
import json
import time, threading
from websocket import create_connection
import gzip
import time
cps = [{'currency': 'act'}, {'currency': 'aidoc'}, {'currency': 'bcx'}, {'currency': 'bifi'}, {'currency': 'btm'}, {'currency': 'cvc'},  {'currency': 'dat'}, {'currency': 'dbc'}, {'currency': 'gnt'}, {'currency': 'gnx'}, {'currency': 'itc'}, {'currency': 'mco'}, {'currency': 'mds'}, {'currency': 'nas'}, {'currency': 'pay'}, {'currency': 'propy'}, {'currency': 'qash'}, {'currency': 'qun'}, {'currency': 'req'}, {'currency': 'rpx'}, {'currency': 'sbtc'}, {'currency': 'smt'}, {'currency': 'swftc'}, {'currency': 'topc'}, {'currency': 'wax'}, {'currency': 'wicc'},{'currency': 'zrx'}]
cp = {'btc':14000,'usdt':1,'usd':1}
class DummyClient(WebSocketClient):
    global cp
    def opened(self):
        self.send("")

    def closed(self, code, reason=None):
        print("Closed down", code, reason)
        ws = DummyClient('wss://stream.binance.com:9443/ws/!ticker@arr', protocols=['chat'])
        ws.connect()
        ws.run_forever()

    def received_message(self, m):
        #print(m)
        jsonmessage = json.loads(str(m))
        #print(jsonmessage)
        for coin in jsonmessage:
            if coin['s'].endswith('BTC'):
                if coin['s'][:-3].lower() != 'usdt':
                    cp[coin['s'][:-3].lower()] = float(coin['c']) * cp['btc']
            elif coin['s'] == 'BTCUSDT':
                cp['btc'] = float(coin['c'])
        #print(cp)
        #print('1')

    def GetCp(self):
        return self.cp


def loop():
    try:
        ws = DummyClient('wss://stream.binance.com:9443/ws/!ticker@arr', protocols=['chat'])
        ws.connect()
        ws.run_forever()
        #ws.run()
        #print(ws.GetCp())
    except KeyboardInterrupt:
        ws.close()

def loop2():
    while True:
        time.sleep(3)
        try:
            for bi in cps:
                MySocket(bi['currency'])
        except Exception as e:
            print('Error:', e)

def MySocket(bi):
    try:
        #print(bi)
        #print("{'req': 'market." + bi + "btc.detail', 'id': 'id12'}")
        tradeStr = '{"req": "market.' + bi + 'btc.detail", "id": "id12"}'
        ws = create_connection("wss://api.huobipro.com/ws")
        ws.send(tradeStr)
        while (1):
            compressData = ws.recv()
            result = gzip.decompress(compressData).decode('utf-8')
            if result[:7] == '{"ping"':
                ts = result[8:21]
                pong = '{"pong":' + ts + '}'
                ws.send(pong)
                ws.send(tradeStr)
            else:
                #print(result)
                myprice = json.loads(result)
                cp[bi] = float(myprice['data']['close']) * cp['btc']
                #print(cp[bi])
                break
    except KeyboardInterrupt:
        ws.close()

if __name__ == '__main__':
    t = threading.Thread(target=loop, name='LoopThread')
    t.start()
    t2 = threading.Thread(target=loop2, name='LoopThread2')
    t2.start()
    #MySocket('itc')

def StartSocket():
    t = threading.Thread(target=loop, name='LoopThread')
    t.start()
    t2 = threading.Thread(target=loop2, name='LoopThread2')
    t2.start()

def GetPrice(coinjson):
    price = 0.0
    for i in coinjson.keys():
        if i in cp.keys():
            price = price + coinjson[i] * cp[i]
            price = int(price * 100)/100
    return price